<template>
  <div>
    <el-page-header class="goback" @back="goBack"> </el-page-header>

    <!-- 房号信息标签页 -->
    <div class="yonghu">
      <el-tabs :tab-position="tabPosition">
        <el-tab-pane label="房号信息"></el-tab-pane>
      </el-tabs>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
        style="margin-top: 20px"
      >
        <!-- 栅格布局：单元名称 + 幢号 -->
        <el-row :gutter="100">
          <el-col :span="10">
            <el-form-item label="单元名称" prop="unitname">
              <el-input
                v-model="ruleForm.unitname"
                placeholder="请输入单元名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="幢号" prop="buildnum">
              <el-input
                v-model="ruleForm.buildnum"
                placeholder="请输入幢号"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 栅格布局：楼层号 + 房号 -->
        <el-row :gutter="100">
          <el-col :span="10">
            <el-form-item label="楼层号" prop="storeynum">
              <el-input
                v-model="ruleForm.storeynum"
                placeholder="请输入楼层号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="房号" prop="homenum">
              <el-input
                v-model="ruleForm.homenum"
                placeholder="请输入房号"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 栅格布局：住客姓名（带对话框） + 入住状态 -->
        <el-row :gutter="100">
          <el-col :span="10">
            <el-form-item label="住客姓名" prop="homename">
              <el-input
                v-model="ruleForm.homename"
                @click.native="dialogVisible = true"
                placeholder="请选择或输入住客姓名"
                readonly
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="入住状态" prop="homestatus">
              <el-select
                v-model="ruleForm.homestatus"
                placeholder="请选择状态"
                style="width: 100%"
              >
                <el-option label="已入住" :value="1"></el-option>
                <el-option label="未入住" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 房屋信息：带提示tooltip -->
        <el-row :gutter="100">
          <el-col :span="20" style="width: 100%">
            <el-tooltip
              content="可填写：1.房屋基本信息 2.房屋设备信息 3.未来规划"
              placement="top"
              popper-class="my-tooltip"
            >
              <span class="doubt">?</span>
            </el-tooltip>
            <el-form-item label="房屋信息" prop="homemessage">
              <el-input
                v-model="ruleForm.homemessage"
                type="textarea"
                :rows="6"
                placeholder="请填写房屋信息"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 家庭成员：带提示tooltip和字数限制 -->
        <el-row :gutter="100">
          <el-col :span="20" style="width: 100%">
            <el-tooltip
              content="可录入：1.主要成员 2.健康状况 3.每日体温检测"
              placement="top"
              popper-class="my-tooltip"
            >
              <span class="doubt">?</span>
            </el-tooltip>
            <el-form-item label="家庭成员" prop="homesuggestion">
              <el-input
                v-model="ruleForm.homesuggestion"
                type="textarea"
                :rows="6"
                placeholder="请填写家庭成员"
                maxlength="100"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 智能设备标签页 -->
    <div class="yonghu">
      <el-tabs :tab-position="tabPosition">
        <el-tab-pane label="智能设备"></el-tab-pane>
      </el-tabs>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
        style="margin-top: 20px"
      >
        <!-- 栅格布局：洗衣机数量 + Wi-Fi名称 -->
        <el-row :gutter="100">
          <el-col :span="10">
            <el-form-item label="洗衣机数量" prop="washnum">
              <el-input
                v-model="ruleForm.washnum"
                placeholder="请输入洗衣机数量"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="WI-FI名称" prop="wifiname">
              <el-input
                v-model="ruleForm.wifiname"
                placeholder="请输入WI-FI名称"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 栅格布局：空调数量 + 智能设备状态 -->
        <el-row :gutter="100">
          <el-col :span="10">
            <el-form-item label="空调数量" prop="airnum">
              <el-input
                v-model="ruleForm.airnum"
                placeholder="请输入空调数量"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="设备状态" prop="smartstatus">
              <el-select
                v-model="ruleForm.smartstatus"
                placeholder="请选择状态"
                style="width: 100%"
              >
                <el-option label="完好" :value="1"></el-option>
                <el-option label="待维修" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 家居设备标签页 -->
    <div class="yonghu">
      <el-tabs :tab-position="tabPosition">
        <el-tab-pane label="家居设备"></el-tab-pane>
      </el-tabs>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
        style="margin-top: 20px"
      >
        <!-- 栅格布局：书桌数量 + 椅子数量 -->
        <el-row :gutter="100">
          <el-col :span="10">
            <el-form-item label="书桌数量" prop="homedesk">
              <el-input
                v-model="ruleForm.homedesk"
                placeholder="请输入书桌数量"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="椅子数量" prop="homechair">
              <el-input
                v-model="ruleForm.homechair"
                placeholder="请输入椅子数量"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 栅格布局：衣橱数量 + 家居设备状态 -->
        <el-row :gutter="100">
          <el-col :span="10">
            <el-form-item label="衣橱数量" prop="homeclothes">
              <el-input
                v-model="ruleForm.homeclothes"
                placeholder="请输入衣橱数量"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="设备状态" prop="familystatus">
              <el-select
                v-model="ruleForm.familystatus"
                placeholder="请选择状态"
                style="width: 100%"
              >
                <el-option label="完好" :value="1"></el-option>
                <el-option label="待维修" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 保存/返回按钮 -->
    <div class="ananan">
      <el-button @click="baocun" type="success">保存</el-button>
      <el-button @click="goBack" type="primary">返回</el-button>
    </div>

    <!-- 住客姓名选择对话框（整合第二份代码功能） -->
    <el-dialog title="住客姓名选择" width="60%" :visible.sync="dialogVisible">
      <!-- 自定义/复制 切换 -->
      <el-radio-group v-model="radioType" style="margin-bottom: 20px">
        <el-radio label="custom">自定义输入</el-radio>
        <el-radio label="copy">从用户列表选择</el-radio>
      </el-radio-group>

      <!-- 自定义输入模式 -->
      <el-input
        v-model="customUserName"
        placeholder="请输入住客姓名"
        v-if="radioType === 'custom'"
        style="width: 100%"
      />

      <!-- 列表选择模式 -->
      <div v-else style="width: 100%">
        <!-- 搜索框 -->
        <el-input
          v-model="searchUsername"
          placeholder="请输入用户账号搜索"
          style="width: 60%; margin-bottom: 15px"
        ></el-input>
        <el-button type="primary" size="medium" @click="searchUser">
          <i class="el-icon-search"></i> 搜索
        </el-button>

        <!-- 用户列表 -->
        <el-table
          :data="tableData"
          stripe
          style="width: 100%; margin-bottom: 15px"
          border
          size="medium"
        >
          <el-table-column
            prop="id"
            label="ID"
            width="80px"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="username"
            label="用户账号"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="homeaddress"
            label="家庭住址"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="type"
            label="用户类型"
            align="center"
          ></el-table-column>
          <el-table-column label="操作" width="80px" align="center">
            <template slot-scope="scope">
              <el-button
                type="success"
                icon="el-icon-plus"
                circle
                size="mini"
                @click="addUser(scope.row)"
                title="选择该用户"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <el-pagination
          style="text-align: center; margin-bottom: 15px"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage4"
          :page-sizes="[7, 10, 20, 30]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>

        <!-- 已选结果 -->
        <h4 style="margin-bottom: 10px">已选用户</h4>
        <el-table
          :data="selectedUserList"
          stripe
          style="width: 100%"
          border
          size="medium"
        >
          <el-table-column
            prop="id"
            label="ID"
            width="80px"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="username"
            label="用户账号"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="homeaddress"
            label="家庭住址"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="type"
            label="用户类型"
            align="center"
          ></el-table-column>
          <el-table-column label="操作" width="80px" align="center">
            <template slot-scope="scope">
              <el-button
                type="danger"
                icon="el-icon-minus"
                circle
                size="mini"
                @click="removeUser(scope.row)"
                title="取消选择"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 对话框底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmUserSelect"
          >确认选择</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>


<script>
export default {
  data() {
    return {
      // 分页相关
      currentPage4: 1,
      pageSize: 7,
      total: 0,
      searchUsername: "",
      tableData: [],
      selectedUserList: [],
      customUserName: "",

      // 对话框相关
      dialogVisible: false,
      radioType: "custom",

      // 基础配置
      tabPosition: "left",
      token: "",
      id: "",

      // 表单数据
      ruleForm: {
        unitname: "",
        buildnum: "",
        storeynum: "",
        homenum: "",
        homename: "",
        homestatus: "",
        homemessage: "",
        homesuggestion: "",
        washnum: "",
        wifiname: "",
        airnum: "",
        smartstatus: "",
        homedesk: "",
        homechair: "",
        homeclothes: "",
        familystatus: "",
      },

      rules: {
        // 房号信息校验
        unitname: [
          { required: true, message: "单元名称不能为空", trigger: "blur" },
        ],
        buildnum: [
          { required: true, message: "幢号不能为空", trigger: "blur" },
        ],
        storeynum: [
          { required: true, message: "楼层号不能为空", trigger: "blur" },
        ],
        homenum: [{ required: true, message: "房号不能为空", trigger: "blur" }],
        homename: [
          { required: true, message: "住客姓名不能为空", trigger: "blur" },
        ],
        homestatus: [
          { required: true, message: "请选择入住状态", trigger: "change" },
        ],
        homemessage: [
          { required: true, message: "请填写房屋信息", trigger: "blur" },
        ],
        homesuggestion: [
          { required: true, message: "请填写家庭成员", trigger: "blur" },
        ],
        // 智能设备校验
        washnum: [
          { required: true, message: "洗衣机数量不能为空", trigger: "blur" },
        ],
        wifiname: [
          { required: true, message: "WI-FI名称不能为空", trigger: "blur" },
        ],
        airnum: [
          { required: true, message: "空调数量不能为空", trigger: "blur" },
        ],
        smartstatus: [
          { required: true, message: "请选择智能设备状态", trigger: "change" },
        ],
        // 家居设备校验
        homedesk: [
          { required: true, message: "书桌数量不能为空", trigger: "blur" },
        ],
        homechair: [
          { required: true, message: "椅子数量不能为空", trigger: "blur" },
        ],
        homeclothes: [
          { required: true, message: "衣橱数量不能为空", trigger: "blur" },
        ],
        familystatus: [
          { required: true, message: "请选择家居设备状态", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.token =
      localStorage.getItem("token") || sessionStorage.getItem("token");
    this.id = this.$route.query.id;
    if (this.id) {
      this.getDetailData(); 
    }
  
    this.getUserList();
  },
  methods: {
 
    baocun() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) return false;

        this.$confirm("确定保存该房号信息吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$axios
              .post("http://community.byesame.com/house/updatenumList", {
                ...this.ruleForm,
                token: this.token,
                id: this.id,
                h_id: this.id,
              })
              .then(() => {
                this.$router.push("/house/number");
                this.$message.success("房号设备信息更新成功");
              })
              .catch((err) => {
                this.$message.error("保存失败，请稍后重试");
                console.error(err);
              });
          })
          .catch(() => {
            this.$message.info("已取消保存");
          });
      });
    },

  
    goBack() {
      this.$router.push("/house/number");
    },

  
    async getDetailData() {
      try {
        const res = await this.$axios.get(
          `http://community.byesame.com/house/getDetailId?id=${this.id}&token=${this.token}`
        );
        if (res.data && res.data.length) {
          this.ruleForm = { ...res.data[0] };
  
          this.customUserName = res.data[0].homename || "";
        }
      } catch (err) {
        console.error("获取详情失败：", err);
        this.$message.error("加载数据失败");
      }
    },

    searchUser() {
      this.currentPage4 = 1; 
      this.getUserList();
    },

    getUserList() {
      this.$axios
        .get(
          `http://community.byesame.com/users/getUserList?username=${
            this.searchUsername
          }&currPage=${this.currentPage4 - 1}&pageNum=${this.pageSize}`
        )
        .then((res) => {
          if (res.status === 200) {
            this.tableData = res.data.data || [];
            this.total = res.data.total || 0;
          }
        })
        .catch((err) => {
          console.error("获取用户列表失败：", err);
          this.$message.error("加载用户列表失败");
        });
    },

 
    handleSizeChange(val) {
      this.pageSize = val;
      this.getUserList();
    },

 
    handleCurrentChange(val) {
      this.currentPage4 = val;
      this.getUserList();
    },

  
    addUser(row) {
  
      const isExist = this.selectedUserList.some((item) => item.id === row.id);
      if (!isExist) {
        this.selectedUserList.push({ ...row });
      } else {
        this.$message.warning("该用户已在已选列表中");
      }
    },

    removeUser(row) {
      this.selectedUserList = this.selectedUserList.filter(
        (item) => item.id !== row.id
      );
    },

    confirmUserSelect() {
      if (this.radioType === "custom") {

        this.ruleForm.homename = this.customUserName;
      } else {
   
        if (this.selectedUserList.length > 0) {
          this.ruleForm.homename = this.selectedUserList[0].username;
        } else {
          this.$message.warning("请至少选择一个用户");
          return;
        }
      }
      this.dialogVisible = false;
    },
  },
};
</script>

<style scoped>
.yonghu {
  margin-top: 1.875rem;
}
.goback {
  color: rgb(2, 154, 219);
  border: 0;
  cursor: pointer;
}
.demo-ruleForm {
  width: 95%;
  margin: 0 auto;
}

.el-row {
  margin-bottom: 20px;
}
.el-col {
  padding: 0 10px;
}

.doubt {
  display: inline-block;
  background-color: #00bfff;
  color: #fff;
  text-align: center;
  font-size: 14px;
  line-height: 18px;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  margin-left: 10px;
  cursor: pointer;
}
/* 按钮区域 */
.ananan {
  float: right;
  margin: 20px 2.5rem;
}
.ananan el-button {
  margin-left: 10px;
}
/* 表格样式 */
.el-table {
  margin-top: 10px;
}
/* 对话框样式 */
.el-dialog__body {
  max-height: 60vh;
  overflow-y: auto;
}
</style>